package com.example.testapp.ui.mine

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.SwitchCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.testapp.config.ConfigHelper
import com.example.testapp.databinding.FragmentMineBinding

class MineFragment : Fragment() {

    private var _binding: FragmentMineBinding? = null
    private val binding get() = _binding!!
    
    private lateinit var switchAutoBackup: SwitchCompat
    private lateinit var switchAccountingReminder: SwitchCompat
    private lateinit var switchExpressRecognition: SwitchCompat
    private lateinit var tvImageApiStatus: TextView
    private lateinit var tvAiApiStatus: TextView

    // 请求码
    private companion object {
        private const val REQUEST_CODE_IMAGE_API_CONFIG = 100
        private const val REQUEST_CODE_AI_API_CONFIG = 101
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val mineViewModel = ViewModelProvider(this).get(MineViewModel::class.java)

        _binding = FragmentMineBinding.inflate(inflater, container, false)
        val root: View = binding.root

        // 初始化控件
        initViews()
        // 加载配置到UI
        loadConfig()
        // 设置监听器
        setupListeners()

        // 保留原有代码
        val textView: TextView = binding.textMine
        mineViewModel.text.observe(viewLifecycleOwner) { textView.text = it }
        
        return root
    }

    private fun initViews() {
        // 获取开关控件引用
        switchAutoBackup = binding.switchAutoBackup
        switchAccountingReminder = binding.switchAccountingReminder
        switchExpressRecognition = binding.switchExpressRecognition
        
        // 获取API状态文本
        tvImageApiStatus = binding.tvImageApiStatus
        tvAiApiStatus = binding.tvAiApiStatus
    }
    
    /**
     * 从持久化存储加载配置到UI
     */
    private fun loadConfig() {
        // 加载开关状态
        switchAutoBackup.isChecked = ConfigHelper.isAutoBackupEnabled(requireContext())
        switchAccountingReminder.isChecked = ConfigHelper.isAccountingReminderEnabled(requireContext())
        switchExpressRecognition.isChecked = ConfigHelper.isExpressRecognitionEnabled(requireContext())
        
        // 加载API状态
        val imageApiProvider = ConfigHelper.getImageApiProvider(requireContext())
        val aiApiProvider = ConfigHelper.getAiApiProvider(requireContext())
        
        // 更新UI显示
        tvImageApiStatus.text = if (imageApiProvider.isEmpty()) "未设置" else imageApiProvider
        tvAiApiStatus.text = if (aiApiProvider.isEmpty()) "未设置" else aiApiProvider
    }
    
    private fun setupListeners() {
        // 自动备份开关监听
        switchAutoBackup.setOnCheckedChangeListener { buttonView, isChecked ->
            // 保存配置到持久化存储
            val success = ConfigHelper.setAutoBackupEnabled(requireContext(), isChecked)
            if (success) {
                Toast.makeText(context, "自动备份：${if (isChecked) "开启" else "关闭"}", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(context, "设置保存失败", Toast.LENGTH_SHORT).show()
                // 恢复UI状态
                buttonView.isChecked = !isChecked
            }
        }
        
        // 记账提醒开关监听
        switchAccountingReminder.setOnCheckedChangeListener { buttonView, isChecked ->
            // 保存配置到持久化存储
            val success = ConfigHelper.setAccountingReminderEnabled(requireContext(), isChecked)
            if (success) {
                Toast.makeText(context, "记账提醒：${if (isChecked) "开启" else "关闭"}", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(context, "设置保存失败", Toast.LENGTH_SHORT).show()
                // 恢复UI状态
                buttonView.isChecked = !isChecked
            }
        }
        
        // 快递单据识别开关监听
        switchExpressRecognition.setOnCheckedChangeListener { buttonView, isChecked ->
            // 保存配置到持久化存储
            val success = ConfigHelper.setExpressRecognitionEnabled(requireContext(), isChecked)
            if (success) {
                Toast.makeText(context, "快递单据识别：${if (isChecked) "开启" else "关闭"}", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(context, "设置保存失败", Toast.LENGTH_SHORT).show()
                // 恢复UI状态
                buttonView.isChecked = !isChecked
            }
        }
        
        // 图片识别API整行点击
        binding.layoutImageApi.setOnClickListener {
            // 启动图片识别API配置页面
            val intent = ApiConfigActivity.newIntent(
                requireContext(),
                "图片识别API配置",
                true,
                ConfigHelper.getImageApiProvider(requireContext()),
                ConfigHelper.getImageApiUrl(requireContext()),
                ConfigHelper.getImageApiKey(requireContext())
            )
            startActivityForResult(intent, REQUEST_CODE_IMAGE_API_CONFIG)
        }
        
        // AI API整行点击
        binding.layoutAiApi.setOnClickListener {
            // 启动AI API配置页面
            val intent = ApiConfigActivity.newIntent(
                requireContext(),
                "AI API配置",
                false,
                ConfigHelper.getAiApiProvider(requireContext()),
                ConfigHelper.getAiApiUrl(requireContext()),
                ConfigHelper.getAiApiKey(requireContext())
            )
            startActivityForResult(intent, REQUEST_CODE_AI_API_CONFIG)
        }
    }
    
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK && data != null) {
            when (requestCode) {
                REQUEST_CODE_IMAGE_API_CONFIG -> {
                    // 处理图片识别API配置结果
                    handleApiConfigResult(data, true)
                }
                REQUEST_CODE_AI_API_CONFIG -> {
                    // 处理AI API配置结果
                    handleApiConfigResult(data, false)
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }
    
    /**
     * 处理API配置结果
     * @param data 返回的数据
     * @param isImageApi 是否为图片API配置
     */
    private fun handleApiConfigResult(data: Intent, isImageApi: Boolean) {
        val provider = data.getStringExtra(ApiConfigActivity.RESULT_PROVIDER) ?: ""
        val apiUrl = data.getStringExtra(ApiConfigActivity.RESULT_API_URL) ?: ""
        val apiKey = data.getStringExtra(ApiConfigActivity.RESULT_API_KEY) ?: ""
        
        // 保存配置到持久化存储
        val success: Boolean
        if (isImageApi) {
            // 保存图片识别API配置
            success = ConfigHelper.saveImageApiConfig(requireContext(), provider, apiUrl, apiKey)
            if (success) {
                // 更新图片识别API状态
                tvImageApiStatus.text = provider
                Toast.makeText(context, "图片识别API配置已保存", Toast.LENGTH_SHORT).show()
            }
        } else {
            // 保存AI API配置
            success = ConfigHelper.saveAiApiConfig(requireContext(), provider, apiUrl, apiKey)
            if (success) {
                // 更新AI API状态
                tvAiApiStatus.text = provider
                Toast.makeText(context, "AI API配置已保存", Toast.LENGTH_SHORT).show()
            }
        }
        
        // 处理保存失败情况
        if (!success) {
            Toast.makeText(context, "API配置保存失败", Toast.LENGTH_SHORT).show()
        }
    }

    // 弃用原始对话框方法，保留API以便兼容
    @Deprecated("使用ApiConfigActivity替代")
    private fun showApiConfigDialog(title: String, isImageApi: Boolean) {
        // 启动对应的配置Activity
        if (isImageApi) {
            val intent = ApiConfigActivity.newIntent(
                requireContext(),
                title,
                true,
                ConfigHelper.getImageApiProvider(requireContext()),
                ConfigHelper.getImageApiUrl(requireContext()),
                ConfigHelper.getImageApiKey(requireContext())
            )
            startActivityForResult(intent, REQUEST_CODE_IMAGE_API_CONFIG)
        } else {
            val intent = ApiConfigActivity.newIntent(
                requireContext(),
                title,
                false,
                ConfigHelper.getAiApiProvider(requireContext()),
                ConfigHelper.getAiApiUrl(requireContext()),
                ConfigHelper.getAiApiKey(requireContext())
            )
            startActivityForResult(intent, REQUEST_CODE_AI_API_CONFIG)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 